$NG.AllReady(function (page, { useValuesChange, useDataIndexChange, useUpdateRows, useUpdateRow }) {
    const mstform = $NG.getCmpApi("p_form_equipment_chg");
    const dgrid1 = $NG.getCmpApi("p_form_equipment_chg_d");
    const dgrid2 = $NG.getCmpApi("p_form_equipment_chg_impl");
    const dgrid3 = $NG.getCmpApi("p_form_equipment_chg_svc");
    const dgrid4 = $NG.getCmpApi("p_form_equipment_chg_rd");
    
    const project_amt = {
        _amt :0,
        //变更含税
        _amt_bg:0,
        //未税
        _amt_ws:0,
        sum:function(){
            $NG.updateState((updater)=>{
                updater.data.p_form_equipment_chg.setProps({
                    u_total_cost_amt_vat:this._amt,
                    u_total_cost_amt:this._amt_ws,
                    u_total_cost_change:this._amt_bg
                })
            })
        },
        set amt(value){
            this._amt = Number(value)
            this.sum()
        },
        get amt(){
            return this._amt
        },
        set amt_bg(value){
            this._amt_bg = Number(value)
            this.sum()
        },
        get amt_bg(){
            return this._amt_bg
        },
        set amt_ws(value){
            this._amt_ws = Number(value)
            this.sum()
        },
        get amt_ws(){
            return this.amt_ws
        }
    }
    ////////////////////////////////////////////////////////////--init--////////////////////////////////////////////////////////////
    if (mstform) {
      getCntCount("p_form_equipment_chg", "u_cnt_id", () => {
        getCntMInfoByPhid();
        getSbqdDetailByCnt();
        danjvchaxun()
      });
      getPtInfoByPhid();
      cntMFilter();
    }
    ////////////////////////////////////////////////////////////--useValuesChange--////////////////////////////////////////////////////////////
    useValuesChange(({ args }) => {
      console.log(`项目监听`, args);
      getPtInfoByPhid();
      getCntCount("p_form_equipment_chg", "u_cnt_id", () => {
        getCntMInfoByPhid();
        getSbqdDetailByCnt();
      });
      danjvchaxun()
    }, "p_form_equipment_chg.phid_pc");
    //监听合同
    useValuesChange(({ args }) => {
      console.log(`合同监听`, args);
      getCntMInfoByPhid();
    }, "p_form_equipment_chg_impl.u_cnt_id");
    ////////////////////////////////////////////////////////////--useUpdateRows--////////////////////////////////////////////////////////////
    let project_total_amt = 0
      let nfb_amt_vat = 0
      let ncg_amt_vat = 0
      let nzz_amt_vat = 0
      let nfb_amt = 0
      let ncg_amt = 0
      let nzz_amt = 0
      let ss_amt = 0
      let cg_amt = 0
      let zz_amt = 0
      let nfb_b = 0
      let ncg_b = 0
      let nzz_b = 0
      let ss_b = 0
      let cg_b = 0
      let zz_b = 0
      let onLock = true
      useUpdateRow(({args})=>{
        const _data = args[0]
        _data.u_sub_cost_vat = (Number(_data.u_sub_prc) || 0)* (Number(_data.u_qty) || 0)* (1 + (Number(_data.u_sub_tax_rate) || 0))
        _data.u_pur_cost_vat = (Number(_data.u_pur_prc) || 0)* (Number(_data.u_qty) || 0)* (1 + (Number(_data.u_pur_tax_rate) || 0))
        _data.u_self_cost_vat = (Number(_data.u_self_prc) || 0)* (Number(_data.u_qty) || 0)* (1 + (Number(_data.u_self_tax_rate) || 0))
      },"p_form_equipment_chg_d")
    useUpdateRows(({ args }) => {
        const _arr = args[0]
        totalSum(_arr,"p_form_equipment_chg_d")
        
    }, "p_form_equipment_chg_d");
    
    useUpdateRows(({args})=>{
        const _arr = args[0]
        totalSum(_arr,"p_form_equipment_chg_impl")
        
    },"p_form_equipment_chg_impl")

    useUpdateRows(({args})=>{
        const _arr = args[0]
        totalSum(_arr,"p_form_equipment_chg_svc")
        
    },"p_form_equipment_chg_svc")

    useUpdateRows(({args})=>{
        const _arr = args[0]
        totalSum(_arr,"p_form_equipment_chg_rd")
    },"p_form_equipment_chg_rd")

    function totalSum(data,table){
        while(!onLock){
        }
        onLock = false
        const _arr = data;
        switch(table){
          case "p_form_equipment_chg_d":
              //含税成本
              nfb_amt_vat =0
              ncg_amt_vat =0
              nzz_amt_vat =0
              //未税成本
              nfb_amt =0
              ncg_amt =0
              nzz_amt = 0 
              break
          case "p_form_equipment_chg_impl":
              ss_amt =0
              break
          case "p_form_equipment_chg_svc":
              cg_amt =0
              break;
          case "p_form_equipment_chg_rd":
              zz_amt =0
              break;
        }
        _arr.forEach((item) => {
          item.u_bglx = "normal";
          //汇总表头
          switch(table){
              case "p_form_equipment_chg_d":
                  //含税成本
                  nfb_amt_vat +=(Number(item.u_sub_cost_vat) || 0)
                  ncg_amt_vat +=(Number(item.u_pur_cost_vat) || 0)
                  nzz_amt_vat +=(Number(item.u_self_cost_vat) || 0)
                  //未税成本
                  nfb_amt +=(Number(item.u_sub_cost) || 0)
                  ncg_amt +=(Number(item.u_pur_cost) || 0)
                  nzz_amt +=(Number(item.u_self_cost) || 0)
                  break
              case "p_form_equipment_chg_impl":
                  ss_amt += (Number(item.u_total_impl_amt) || 0)
                  break
              case "p_form_equipment_chg_svc":
                  cg_amt += (Number(item.u_total_svc_amt) || 0)
                  break;
              case "p_form_equipment_chg_rd":
                  zz_amt += (Number(item.u_rd_expenses) || 0)
                  break;
          }
        });
        //汇总总额
      project_total_amt = nfb_amt_vat+ncg_amt_vat+nzz_amt_vat+ss_amt+cg_amt+zz_amt
        //比例
        switch(table){
          case "p_form_equipment_chg_d":
              nfb_b = (Number(nfb_amt_vat/project_total_amt) || 0)
              ncg_b = (Number(ncg_amt_vat/project_total_amt) || 0)
              nzz_b = (Number(nzz_amt_vat/project_total_amt) || 0)
              break
          case "p_form_equipment_chg_impl":
              ss_b = (Number(ss_amt/project_total_amt) || 0)
              break
          case "p_form_equipment_chg_svc":
              cg_b = (Number(cg_amt/project_total_amt) || 0)
              break;
          case "p_form_equipment_chg_rd":
              zz_b = (Number(zz_amt/project_total_amt) || 0)
              break;
      }
        
        $NG.updateState((updater)=>{
          updater.data.p_form_equipment_chg.setProps({
              u_sub_cost_amt_vat:nfb_amt_vat,
              u_pur_cost_amt_vat:ncg_amt_vat,
              u_self_cost_amt_vat:nzz_amt_vat,
              u_sub_cost_amt:nfb_amt,
              u_pur_cost_amt:ncg_amt,
              u_self_cost_amt:nzz_amt,
              u_implement_amt_vat:ss_amt,
              u_implement_amt:ss_amt,
              u_svc_cost_amt_vat:cg_amt,
              u_svc_cost_amt:cg_amt,
              u_sub_cost_ratio:nfb_b,
              u_pur_cost_ratio:ncg_b,
              u_self_cost_ratio:nzz_b,
              u_implement_cost_ratio:ss_b,
              u_svc_cost_ratio:cg_b
          })
        })
        //项目金额变更汇总
        project_amt.amt_bg = project_total_amt
        console.log(`汇总变更`,project_amt.amt_bg,nfb_amt_vat,ncg_amt_vat,nzz_amt_vat,ss_amt,cg_amt,zz_amt);
        onLock = true
        dgrid1.refreshView();
    }
    /**
     * 功能扩展区
     *
     */
    function getPtInfoByPhid() {
      if (mstform.getItem("phid_pc").getValue()) {
        $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
          const datas = JSON.parse(res.data)[0].extendObjects;
          console.log(datas);
          $NG.updateState((updater) => {
            updater.data.p_form_equipment_chg.setProps({
              //项目编码
              u_pc_no: datas.pc_no,
              //项目金额
              approx_contract_fc: datas.approx_contract_fc,
              //计划开工日期
              start_date: datas.start_date,
              //计划完工日期
              end_date: datas.end_date,
              //售前顾问
              u_sqgw: { value: datas.user_sqgw_phid, label: datas.user_sqgw_name },
              //项目经理
              u_project_manager: { value: datas.project_manager_phid, label: datas.project_manager_name },
              //事业部
              u_division: { value: datas.division_phid, label: datas.division_name },
              //组织
              phid_org_phid: { value: datas.phid_org_phid, label: datas.phid_org_name },
              //区域中心
              u_regional_center: { value: datas.regional_center_phid, label: datas.regional_center_name },
              //产品线
              u_product_line: { value: datas.midwife_phid, label: datas.midwife_name },
              //客户名称
              customer: { value: datas.customer_id, label: datas.customer_name },
              //部门
              u_dept: { value: datas.dept_phid, label: datas.dept_name },
              //项目类型
              u_pc_type: { value: datas.type_phid, label: datas.type_name },
              //项目预算组织编码
              budget_org_code: datas.budget_org_no,
              //项目预算组织
              budget_org_phid: { value: datas.budget_org_phid, label: datas.budget_org_name },
            });
          });
        });
      }
    }
  
    function cntMFilter() {
      $NG.updateUI((updater, state) => {
        updater.fieldSetForm.p_form_equipment_chg.u_cnt_id.setProps({
          onBeforeOpen: async () => {
            var phid_pc = mstform.getItem("phid_pc").getValue();
            if (!phid_pc) {
              $NG.alert("请先选择项目");
              return false;
            } else {
              return true;
            }
          },
          ...(!!mstform.getItem("phid_pc").getValue() && {
            clientSqlFilter: {
              bill_type: 1,
              phid_pc: mstform.getItem("phid_pc").getValue(),
            },
          }),
        });
      });
    }
  
    function getCntMInfoByPhid(params) {
      $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt_id").getValue() }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        console.log(datas);
        $NG.updateState((updater) => {
          updater.data.p_form_equipment_chg.setProps({
            u_cnt_no: datas.pcm_no, //合同编号
            start_dt: datas.start_dt, //约定开工时间
            end_dt: datas.end_dt, //约定完工时间
            u_total_cnt_amt_vat:datas.cnt_sum_vat_fc,//合同金额
            u_cnt_amt_vat:datas.cnt_sum_vat_fc,//合同金额
            cnt_sum_vat_fc: datas.cnt_sum_vat_fc, //合同价税合计
            //产品线
            user_product_line: { value: datas.midwife_phid, label: datas.midwife_name },
            //合同类型
            u_cnt_type: { value: datas.pct_id, label: datas.pct_name },
            //甲方单位
            u_customer: { value: datas.customer_id, label: datas.customer_name },
            //乙方单位
            supply: { value: datas.supply_id, label: datas.supply_name },
            //发票类型
            u_invoice_type: { value: datas.invoice_type_phid, label: datas.invoice_type_name },
            //购方信息（客户信息）（收票单位信息）
            //单位名称
            tick_id: { value: datas.tick_id, label: datas.tick_name },
            //单位编码
            tick_no: datas.tick_no,
            //社会信用代码
            tick_unisocialcredit: datas.tick_unisocialcredit,
            //单位地址
            tick_taxaddress: datas.tick_taxaddress,
            //联系电话
            tick_taxtelephone: datas.tick_taxtelephone,
            //银行名称
            tick_taxbankid: { value: datas.tick_taxbankid, label: datas.tick_taxbankname },
            //银行账号
            tick_taxaccountno: datas.tick_taxaccountno,
            //销方信息（供应商信息）（开票单位信息）
            //单位名称
            inv_id: { value: datas.inv_id, label: datas.inv_name },
            //单位编码
            inv_no: datas.inv_no,
            //社会信用代码
            inv_unisocialcredit: datas.inv_unisocialcredit,
            //单位地址
            inv_taxaddress: datas.inv_taxaddress,
            //联系电话
            inv_taxtelephone: datas.inv_taxtelephone,
            //银行名称
            inv_taxbankid: { value: datas.inv_taxbankid, label: datas.inv_taxbankname },
            //银行账号
            inv_taxaccountno: datas.inv_taxaccountno,
          });
        });
      });
    }
  
    // 获取设备清单明细
    function getSbqdDetailByCnt() {
      if (!mstform.getItem("u_cnt_id").getValue()) return;
      $NG.execServer("getSbqdDetailByCnt", { cnt: mstform.getItem("u_cnt_id").getValue() }, function (res) {
        console.log("获取明细", res);
        if (res.count == 0) return;
        //明细数组
        const _data = JSON.parse(res.data);
        console.log(_data);
        const _tempArr = [];
        let projectAmt = 0
        let projectAmt_ws = 0
        _data.forEach((items) => {
          const item = items.extendObjects;
          _tempArr.push({
            u_revenue_type: item.u_revenue_type,
            u_eq_item_name:item.u_equipment_list_name,
            u_revenue_type_EXName: item.ur_exname,
            u_pc_subitem_category: item.u_pc_subitem_category,
            u_eq_item_no: item.u_equipment_list_no,
            u_cnt_item_no: item.u_cnt_item_no,
            u_cnt_item: item.u_cnt_item,
            u_cnt_item_EXName: item.u_cnt_item_exname,
            u_spec: item.u_spec,
            u_tech_params:item.u_tech_params,
            u_brand: item.u_brand,
            u_brand_EXName: item.u_brand_exname,
            u_is_self: item.u_is_self,
            u_is_standardized: item.u_is_standardized_tech_params,
            u_msunit: item.u_msunit,
            u_msunit_EXName: item.u_msunit_exname,
            u_qty: item.u_qty,
            u_cnt_prc: item.u_cnt_prc,
            u_cnt_amt_vat: item.u_cnt_amt_vat, //合同含税金额
            u_cnt_amt: item.u_cnt_amt,
            u_sub_name:item.u_sub_name,
            u_sub_spec: item.u_sub_ggxh,
            u_sub_item_category: item.u_sub_item_category,
            u_sub_item_category_EXName: item.u_sub_item_category_exname,
            u_sub_guide_prc: item.u_fwgczdj,
            u_sub_prc: item.u_sub_prc,
            u_sub_tax_rate: item.u_sub_tax_rate,
            u_sub_cost: item.u_sub_cost,
            u_sub_cost_vat: item.u_sub_cost_vat,
            u_sub_item:item.u_sub_item,
            u_sub_item_EXName:item.u_sub_item_exname,
            u_pur_name: item.u_pur_name, //拟采购项名称
            u_pur_spec: item.u_pur_ggxh, // 拟采购规格
            u_pur_item_category: item.u_pur_item_category,
            u_pur_item_category_EXName: item.u_pur_item_category_exname,
            u_pur_guide_prc: item.u_cgzdj,
            u_pur_prc: item.u_pur_prc,
            u_pur_tax_rate: item.u_pur_tax_rate,
            u_pur_cost: item.u_pur_cost,
            u_pur_cost_vat: item.u_pur_cost_vat,
            u_pur_item:item.u_pur_item,
            u_pur_item_EXName:item.u_pur_item_exname,
            u_self_name: item.u_self_name, //拟自制名称
            u_self_spec: item.u_self_ggxh,
            u_self_item_category: item.u_self_item_category,
            u_self_item_category_EXName: item.u_self_item_category_exname,
            u_self_item:item.u_self_item,
            u_self_item_EXName:item.u_self_item_exname,
            u_self_prc: item.u_self_prc,
            u_self_tax_rate: item.u_self_tax_rate,
            u_self_cost: item.u_self_cost,
            u_self_cost_vat: item.u_self_cost_vat,
          });
          //汇总项目含税总额
          projectAmt+=(Number(item.u_sub_cost_vat) || 0) + (Number(item.u_pur_cost_vat) || 0) + (Number(item.u_self_cost_vat) || 0)
          projectAmt_ws+=(Number(item.u_sub_cost) || 0) + (Number(item.u_pur_cost) || 0) + (Number(item.u_self_cost) || 0)
        });
        project_amt.amt = projectAmt
        project_amt.amt_ws = projectAmt_ws
        dgrid1.clearRows().then(() => {
          dgrid1.addRows(_tempArr);
          dgrid1.refreshView();
        });
      });
    }
    // 三大费用带出，最新
    function danjvchaxun() {
        let mxLock = true
    if(!mstform.getItem("phid_pc")) return 
        dgrid2.clearRows();
        dgrid3.clearRows();
        dgrid4.clearRows();
        if (dgrid2) {
          $NG.execServer(
            "get_impl_cost_budget_info",
            {
              phid_pc: mstform.getItem("phid_pc").getValue(),
            },
            function (res) {
              console.log(`实施费请求`, res);
              if (res.count == 0) return;
              const data = JSON.parse(res.data);
              console.log(res.data);
              //默认增行,批量新增表体数据
              var gridArr = []; //定义表体数组
              var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
              let total_amt = 0
              for (var i = 0; i < gridCount; i++) {
                var gridObj = {};
                //对表体字段进行赋值,可以取数据库中的值进行赋值
                gridObj.u_bill_no = data[i].extendObjects.bill_no;
                gridObj.u_total_impl_amt = data[i].extendObjects.u_total_impl_amt;
                gridObj.u_total_impl_labor_amt = data[i].extendObjects.u_total_impl_labor_amt;
                gridObj.u_total_daily_amt = data[i].extendObjects.u_total_daily_amt;
                gridObj.u_total_sec_dev_amt = data[i].extendObjects.u_total_sec_dev_amt;
                gridObj.u_source_phid = data[i].extendObjects.phid
                // gridObj.u_invoice_type = data[i].extendObjects.u_invoice_type;
                total_amt = (Number(data[i].extendObjects.u_total_impl_amt) || 0)
                gridArr.push(gridObj);
              }
              console.log(`实施`,total_amt);
              while(!mxLock){}
              mxLock = false
              project_amt.amt = project_amt.amt + total_amt
              mxLock = true
                //调用新增表体行数据的函数
              dgrid2.addRows(gridArr);
            }
          );
        }
        if (dgrid3) {
          $NG.execServer(
            "get_svc_cost_budget_info",
            {
              phid_pc: mstform.getItem("phid_pc").getValue(),
            },
            function (res) {
              console.log(`服务请求`, res);
              if (res.count == 0) return;
              const data = JSON.parse(res.data);
              console.log(res.data);
              //默认增行,批量新增表体数据
              var gridArr = []; //定义表体数组
              var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
              let total_amt = 0
              for (var i = 0; i < gridCount; i++) {
                //对表体字段进行赋值,可以取数据库中的值进行赋值
                var gridObj = {};
                gridObj.u_bill_no = data[i].extendObjects.bill_no;
                gridObj.u_total_svc_amt = data[i].extendObjects.u_total_svc_amt;
                gridObj.u_total_svc_labor_amt = data[i].extendObjects.u_total_svc_labor_amt;
                gridObj.u_total_daily_amt = data[i].extendObjects.u_total_daily_amt;
                gridObj.u_source_phid = data[i].extendObjects.phid
                total_amt = (Number(data[i].extendObjects.u_total_svc_amt) || 0)
                // gridObj.u_invoice_type = data[i].extendObjects.u_invoice_type;
                gridArr.push(gridObj);
              }
              console.log(`服务`,total_amt);
              while(!mxLock){}
              mxLock = false
              project_amt.amt = project_amt.amt + total_amt
              mxLock = true
                //调用新增表体行数据的函数
              dgrid3.addRows(gridArr);
            }
          );
        }
        if (dgrid4) {
          $NG.execServer("getDevCostBudgetInfo", { phid_pc: mstform.getItem("phid_pc").getValue() }, function (res) {
            console.log(`研发费请求`, res);
            if (res.count == 0) return;
            const data = JSON.parse(res.data);
            console.log(res.data);
            //默认增行,批量新增表体数据
            var gridArr = []; //定义表体数组
            var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
            for (var i = 0; i < gridCount; i++) {
              //对表体字段进行赋值,可以取数据库中的值进行赋值
              var gridObj = {};
              gridObj.u_bill_no = data[i].extendObjects.bill_no;
              gridObj.u_rdrg_expenses_total = data[i].extendObjects.u_total_labor_amt;
              gridObj.u_rcfy_total = data[i].extendObjects.u_total_daily_amt;
              gridObj.u_rd_expenses = data[i].extendObjects.u_total_dev_amt;
              gridObj.u_source_phid = data[i].extendObjects.phid
              total_amt = (Number(data[i].extendObjects.u_total_dev_amt) || 0)
                // gridObj.u_invoice_type = data[i].extendObjects.u_invoice_type;
                
              gridArr.push(gridObj);
            }
              console.log(`yanfa `,total_amt);
            while(!mxLock){}
            mxLock = false
            project_amt.amt = project_amt.amt + total_amt
            mxLock = true
            //调用新增表体行数据的函数
            dgrid4.addRows(gridArr);
          });
        }
      }
  
    //获取合同数量
    function getCntCount(table, key, fun) {
      if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
      $NG.execServer("getCntCount", { type: 1, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
        console.log(res, "count");
        switch (res.count) {
          case 0:
            return;
          case 1:
            const datas = JSON.parse(res.data)[0].extendObjects;
            const temp_map = {};
            temp_map[key] = datas.phid;
            temp_map[`${key}_EXName`] = datas.bill_name;
            $NG.updateState((updater) => {
              updater.data[table].setProps({
                ...temp_map,
              });
              setTimeout(() => {
                if (fun) {
                  fun();
                }
              }, 200);
            });
        }
      });
    }
  });
  